
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:eshi/main.dart';
import 'package:eshi/app/shi/data/Config.dart';
import 'package:eshi/app/shi/data/tabtxt_history.dart';

/// 其他历史
class OthersWidget extends StatefulWidget {
  bool isHorizontal;
  int currentHistoryId;

  OthersWidget(this.isHorizontal,this.currentHistoryId, {super.key});

  @override
  State<StatefulWidget> createState() => OthersHistoryState();

}

class OthersHistoryState extends State<OthersWidget> {
  int currentHistoryId = 0;

  final  data = TabTxtHistory.all().keys.toList();
  var maxId = 0;
  Timer? _timer; // 用于控制定时

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    currentHistoryId = widget.currentHistoryId;
    maxId = data.length;
  }
  @override
  Widget build(BuildContext context) {
    double pos=0;
    return  GestureDetector(
          onLongPress: (){
              // 每隔1秒执行一次
            _timer = Timer.periodic(Duration(milliseconds: 400), (timer) {
                    setState(() {
                      if(currentHistoryId++>data.length-1){
                        currentHistoryId =0;
                      }
                    });
            });
          },
          onLongPressEnd: (v){
            _timer?.cancel();
            _timer = null;            
            onChangeCurrent();
            print("on pressd");
          },
          onTap: (){
             print("on onTap");
             customWidgetKey.currentState?.handleWillPop();
          },
          onPanEnd: (v){
             print("on panend");
             onChangeCurrent();
          },
          onPanUpdate: (v){
              final posAdd = widget.isHorizontal ? v.delta.dx:  v.delta.dy;
              pos+=posAdd; 
              var n = (pos.abs()/5).toInt();
              if(n>0){
              setState(() {  
                while(n-->0)
                  if(pos>0){
                    if(++currentHistoryId>maxId) currentHistoryId =maxId;
                  }else{
                    if(--currentHistoryId < 0) currentHistoryId = 0;
                  }
                });
                pos=0;
              }
          },
          child:Stack(children: [
             Container(
              color: Colors.grey.withOpacity(0.2),
              padding: EdgeInsets.all(25),
              child: widget.isHorizontal? 
                Row(
                  // 确保 Column 居中（子元素在交叉轴居中）
                ): 
                Column(
                  // 确保 Column 居中（子元素在交叉轴居中）
                  children: [Text("\t"*16) ] 
                )
             ),
            Align(
              alignment: widget.isHorizontal ? Alignment.topCenter :Alignment.centerLeft,
              child: 
              itemsBox()
            )
          ]) 
    );
  }
  onChangeCurrent({int index=-1}){
    if(index>-1) {
      setState(() {
        currentHistoryId =index;  
      });
    }
    final name = currentHistoryId==0 ? "中国历史": data.elementAt(currentHistoryId-1);
    TabTxtHistory.load(name).then((mHistory) =>{
                // Config.lastHistory = mHistory.name;
                mainWidgetKey.currentState?.changeHistory(mHistory)
    });
  }
  Widget itemsBox(){
    return Container(
              color: Colors.blueGrey,
              padding: EdgeInsets.all(10),
              child: widget.isHorizontal? 
                Row(
                  // 确保 Column 居中（子元素在交叉轴居中）
                  mainAxisSize: MainAxisSize.min,
                  children: items(),
                ): 
                Column(
                  // 确保 Column 居中（子元素在交叉轴居中）
                  mainAxisSize: MainAxisSize.min,
                  children: items()
                )
            );
  }

  List<Widget> items(){
    var rt =  <Widget>[];
    for (var indexedEntry in data.indexed) {
        final index = indexedEntry.$1;
        final entry = indexedEntry.$2;
        rt.add(
          InkWell(
              onTap: () {
                Config.lastHistory = entry;
                // TabTxtHistory.load(entry.key).then((mHistory) =>{
                //     mainWidgetKey.currentState?.changeHistory(mHistory)
                // });
                onChangeCurrent(index:index+1);
              },child: Container(padding: EdgeInsets.all(5),
                  child:  Text(entry)
                )
          )
        );
    }
   
    //添加默认项 
    rt.insert(0, InkWell(
              onTap: () {
                Config.lastHistory = null;
                // mainWidgetKey.currentState?.changeHistory(china_history());
                onChangeCurrent(index:0);
              }
              ,child: Container(padding: EdgeInsets.all(5),
                  child:  Text("中国历史")
              )
            )
    );
    //选择标注 
    rt[currentHistoryId] =  Container(
          color: Colors.blue,
          child: rt[currentHistoryId]
    );
    return rt;
  }
}